<template>
	<el-input
	    v-model="name"
	    placeholder="请输入姓名关键字"
	    class="input-with-select"
		style="width:60%"
	>
		<template #prepend>
			<el-cascader 
						 v-model="searchFacultyIds"
						 placeholder="请选择部门"
						 :props="optionsArr"
						 style="width:100%"
						 clearable
						 @change="getFacultyId($event,'2')"
						 />
		</template>
	    <template #append>				
	        <el-button @click="search()"><el-icon><Search /></el-icon></el-button> 
	    </template>        
	</el-input>
	<el-button primary @click.native="addInit">+增加</el-button>
	<el-button warning @click="deleteBatch()">批量删除</el-button>
	<el-button primary @click="echartsBar()">统计图表</el-button> 
	 
<!-- 大表 -->
	<el-table
	  v-loading="loading"
	  :data="tableData"
	  style="width: 100%"
	  stripe
	  ref="multipleTable"
	   @selection-change="handleSelectionChange"
	   :header-cell-style="{background:'#eef1f6',color:'#606266'}"
	>
		<el-table-column min-width="15%" type="selection"></el-table-column>
		<el-table-column prop="name" label="姓名" sortable />
		<el-table-column prop="username" label="用户名" sortable/>
		<el-table-column prop="password" label="密码" sortable />
		<el-table-column prop="politicsStatus" label="政治面貌" sortable />
		<el-table-column prop="sex" label="性别" sortable />
		<el-table-column prop="faculty.description" label="所属部门"/>	
		<el-table-column prop="available" label="账号可用性"/>	
		<el-table-column label="操作" width="120"> 
		   <template #default="scope">
			  <el-button size="small" @click="initEdit(scope.row)"
				type="primary" circle><el-icon><Edit /></el-icon></el-button>
			  <el-button
				size="small"
				type="danger"
				@click="handleDelete(scope.row.id)"
				 circle><el-icon><Delete /></el-icon></el-button>
			</template>				
		</el-table-column>
	</el-table>    
	
	
<!-- 分页组件 -->
	<el-pagination
	  small
	  background
	  layout="prev, pager, next"
		:page-size="pageSize"
		:page-count="pageCount"
		:current-page="currentPage"
		@current-change="haddlePageChange"
	/> 
	  
<!-- 	  <el-radio v-for="" :label="item.name">
		  {{item.name}}
	  </el-radio> -->
	  
<!-- 增加对话框 -->
	<el-dialog v-model="addVisible" title="增加" width="60%" draggable>
	  <el-form :model="form" label-width="80px" :rules="formRules"  class="demo-ruleForm">
		  <el-form-item label="姓名" prop="name">
		    <el-input v-model="form.name" />
		  </el-form-item>
	      <el-form-item label="用户名" prop="username">
	        <el-input v-model="form.username" />
	      </el-form-item>
		  <el-form-item label="密码" prop="password">
		    <el-input v-model="form.password" />
		  </el-form-item>
		  <el-form-item label="性别">
			  <el-radio-group v-model="form.sex">
			     <el-radio v-for="item in sexList" :label="item.item_text">
			    		  {{item.item_text}}
			     </el-radio>
			  </el-radio-group>
		  </el-form-item>
		  <el-form-item label="政治面貌">
		    <el-radio-group v-model="form.politicsStatus">
		       <el-radio v-for="item in politicsStatusList" :label="item.item_text">
		      		  {{item.item_text}}
		       </el-radio>
		    </el-radio-group>
		  </el-form-item>
		  <el-form-item label="所属部门">
		    <el-cascader
		    			 v-model="selFacultyIds"
		    			 placeholder="请选择部门"
		    			 :props="optionsArr"
		    			 style="width:100%"
		    			 clearable
		    			 @change="getFacultyId($event,'1')"
		    			 />
		  </el-form-item>
		  <el-form-item label="账号可用性">
		    <el-input v-model="form.available" />
		  </el-form-item>	  
	   </el-form>
	  <template #footer>
	    <span class="dialog-footer">
	      <el-button @click="addVisible = false">取消</el-button>
	      <el-button type="primary" @click="addSubmit()">提交</el-button>
	    </span>
	  </template>
	</el-dialog>
		
	<!--  修改对话框 -->
	<el-dialog v-model="editVisible" title="修改" width="60%" draggable>
	  <el-form :model="form" label-width="80px" :rules="formRules"  class="demo-ruleForm">
	      <el-form-item label="姓名" prop="name">
	        <el-input v-model="form.name" />
	      </el-form-item>
	      <el-form-item label="用户名" prop="username">
	        <el-input v-model="form.username" />
	      </el-form-item>
	      <el-form-item label="密码" prop="password">
	        <el-input v-model="form.password" />
	      </el-form-item>
	      <el-form-item label="性别">
	      	<el-radio-group v-model="form.sex">
	      		<el-radio v-for="item in sexList" :label="item.item_text">
					{{item.item_text}}
	      		</el-radio>
	      	</el-radio-group>
	      </el-form-item>
	      <el-form-item label="政治面貌">
	        <el-radio-group v-model="form.politicsStatus">
	           <el-radio v-for="item in politicsStatusList" :label="item.item_text">
	          		{{item.item_text}}
	           </el-radio>
	        </el-radio-group>
	      </el-form-item>
	      <el-form-item label="所属部门">
	        <el-cascader
	        			 v-model="selFacultyIds"
	        			 placeholder="请选择部门"
	        			 :props="optionsArr"
	        			 style="width:100%"
	        			 clearable
	        			 @change="getFacultyId($event,'1')"
	        			 />
	      </el-form-item>
	      <el-form-item label="账号可用性">
	        <el-input v-model="form.available" />
	      </el-form-item>	
	   </el-form>
	  <template #footer>
	    <span class="dialog-footer">
	      <el-button @click="editVisible = false">取消</el-button>
	      <el-button type="primary" @click="editSubmit()">提交</el-button>
	    </span>
	  </template>
	</el-dialog>  
	<el-dialog v-model="echartsVisible" title="统计图表" width="70%" draggable> <!-- draggable代表可拖拽 -->
			<div id="myChart" style="width:1100px; height:400px" ></div>
	    <span class="dialog-footer">
	      <el-button @click="echartsVisible = false" >关闭</el-button>
	     </span>
	</el-dialog> 	  
</template>

<script setup>
	import {ref,toRefs,reactive,onMounted,getCurrentInstance} from 'vue'	
	
	let { proxy } = getCurrentInstance();
	//每页几条数据，初始值设置为3条，数据量多的话可以设置更大一些，例如15
	var pageSize=ref(5)
	//当前是第几页，初值是第一页
	var currentPage=ref(1)
	//总页数
	var pageCount=ref(0)
	//表格用数据，初始为空
	let tableData=ref([]);
	//增加对话框显示与否
	let addVisible = ref(false)
	//修改对话框显示与否
	let editVisible=ref(false)
	//加载
	let loading = ref(true)
	//修改或增加的一个对象
	let form=ref({});
	//对话框中联动下拉后选中某一院系
	let selFacultyIds = ref([])
	//搜索栏中联动下拉后选中某一院系
	let searchFacultyIds = ref([])
	//批量删除的选中的选项
	let multipleSelection=ref([]);
	//按姓名搜索
	let name=ref('')
	//按院系搜索
	let facultyId=ref(0)
	//字典政治面貌
	let	politicsStatusList=ref([])
	//字典性别
	let	sexList=ref([])
	//分页对象
	let pagination = ref({})
	//获取查询数据的对象
	let objForSearch = ref({})


	//获取表单数据
	function getTableData(){
		pagination.value=({
			"pagination":{
				"pageNo":currentPage,
				"pageSize":pageSize,
				}
		})
		proxy.$http.post(
		'/userFindAll',
		pagination.value,
		{"headers":{"token":window.sessionStorage.getItem("token")}})
		.then(res => {
			loading.value=false
			tableData.value=res.data.data;//把获取的服务端数据数组传递给tableData
			//后台返回总页数
			pageCount.value=res.data.totalPages
		})
		.catch(err => {
			console.log(err)
		});
	}
	
	//获得字典数据
	function getDictItem(){
		proxy.$http.get(
		'/dictItemFindAll',
		{"headers":{"token":window.sessionStorage.getItem("token")}})
		.then(res => {
			res.data.data.forEach(function(item){ 
				if(item.dictionary.id == 1){
					sexList.value.push(item)
				}else{
					politicsStatusList.value.push(item)
				}
			})
		})
		.catch(err => {
			console.log(err)
		});
	}
	
	//钩子函数，组件加载完自动执行
	onMounted(()=>{
		getTableData();  //请求第一页的表格数据
	});
	
	//学院专业联动下拉选项数据
	let optionsArr=reactive({
	  lazy:true,
	  checkStrictly: true,
	  // 打开对话框时，自动懒加载下拉框
	  lazyLoad:(node,resolve)=>{ // node表示节点（子节点或父节点）
		  getFacultyOptions(node,resolve) // 一层一层获取数据
	  },
	})
	
	//增加初始化
	function addInit(){
		form.value={}
		sexList.value=[]
		politicsStatusList.value=[]
		selFacultyIds.value=[]
		addVisible.value = true
		getDictItem()
	}
	
	//学院专业联动下拉获取数据
	function getFacultyOptions(node,resolve){
		setTimeout(() => {
		  const { level } = node;
			// 第一级
			if (node.level == 0) {
			  proxy.$http.get(
			  '/findSchoolFromFaculty',
			  {"headers":{"token":window.sessionStorage.getItem("token")}}
			  ).then((response) => {
				const nodes = response.data.data.map((item, index) => ({
				  value: item.id,
				  label: item.description,
				  leaf:node.level >= 2 //学院都不是叶子节点，还可以有下一级
				}));
				resolve(nodes);
			  })
			}
			
			// 第二级，点击第一级时才调用
			if(node.level == 1){
			  //在二级节点时，node.value是一级节点的value值 
			  proxy.$http.get(
			  '/findDepartmentBySchoolId?id='+node.value,
			  {"headers":{"token":window.sessionStorage.getItem("token")}}
			  ).then((response) => {  
				const nodes = response.data.data.map((item1, index) => ({
				  value: item1.id,
				  label: item1.description,
				  leaf:true
				}));
				resolve(nodes);
			  })
			}
		}, 100);//异步加载等待
	}
	

	// 修改增加是1，查询是2
	function getFacultyId(event,handle) { // 此方法是获得了专业和学院共两个id，送入数组
		if(handle=='1')
			selFacultyIds.value=event;
		else if(handle=='2')
			searchFacultyIds.value=event;
	}

	//增加提交
	function addSubmit(){
		console.log(selFacultyIds.value)
		// 级联信息需要单独处理
		if(selFacultyIds.value[1] == null){
			form.value.faculty={"id":selFacultyIds.value[0]}
		}else{
			form.value.faculty={"id":selFacultyIds.value[1]}
		}
		//console.log(form.value)
		proxy.$http.post(
		'/userAdd',
		form.value,
		{"headers":{"token":window.sessionStorage.getItem("token")}}) //按增加数据的接口组织url
		.then(res => {
			addVisible.value = false //关闭对话框		
			getTableData();  //更新表格数据
			form.value={}  //清空增加对象
			selFacultyIds.value=[]
			alert(res.data.message)
		})
	}
	
	//点击改变页码时，当前页改变，根据新的URL参数重新获取后台数据
	function haddlePageChange(currentpage){			
		currentPage.value=currentpage;
		getTableData();
	}
	
	//修改对话框显示出来，数据初始化
	const initEdit = (row) => {
		sexList.value=[]
		politicsStatusList.value=[]
		selFacultyIds.value=[]
		editVisible.value = true
		getDictItem();
		form.value=row  //要修改的对象赋值给对话框表单数据
		console.log(row)
		if(row.faculty.parent==undefined){
			selFacultyIds.value=[row.faculty.id]
			console.log(selFacultyIds.value)
		}else{
			selFacultyIds.value=[row.faculty.parent.id,row.faculty.id]
			console.log(selFacultyIds.value)
		}
	}
	
	//修改提交
	const editSubmit=()=>{
		// 单独处理级联下拉数据，只取出专业的id，因为老师直属一个专业
		// 级联信息需要单独处理
		//console.log(selFacultyIds.value[1])
		if(selFacultyIds.value[1] == null){
			form.value.faculty={"id":selFacultyIds.value[0]}
		}else{
			form.value.faculty={"id":selFacultyIds.value[1]}
		}
		proxy.$http.put(
		'/userUpdateByAdmin',
		form.value,
		{"headers":{"token":window.sessionStorage.getItem("token")}},
		).then(res => {								
			editVisible.value = false	//关闭对话框		
			getTableData();  //更新表格数据
			form.value={}  //清空修改对象
			selFacultyIds=[]
			alert(res.data.message)	
		})
	}
	
    
	//按id删除
	const handleDelete = (id) => {
		proxy.$http.delete(
		'/userDelete?id='+id,
		 {"headers":{"token":window.sessionStorage.getItem("token")}}
		)  //根据接口组织删除用url
		.then(res => {			
			getTableData();  //更新表格数据
			alert(res.data.message)
		})
	}
	
	//批量选择
	const handleSelectionChange=(val)=>{ 
		multipleSelection.value = val;
		console.log(multipleSelection.value)
	}
	
	//批量删除
	function deleteBatch(){
		if(multipleSelection.value){
			proxy.$http.post(
			'/userDelete',
			multipleSelection.value,
			{"headers":{"token":window.sessionStorage.getItem("token")}})
			.then(res => {			
				getTableData();  //更新表格数据
				alert(res.data.message)
			})
		}
	}
	

	let search=()=>{
		if(searchFacultyIds.value.length==0 && name.value!=null){
			objForSearch.value = {
				"pagination":{
					"pageNo":currentPage,
					"pageSize":pageSize,
				},
				"conditionList":[
					{"value":name,"key":"name","operator":"LIKE"},
				]
			}
		}else if(searchFacultyIds.value.length!=0 && name.value==null){
			if(searchFacultyIds.value[1] == null){
				facultyId.value=searchFacultyIds.value[0]
			}else{
				facultyId.value=searchFacultyIds.value[1]
			}
			objForSearch.value = {
				"pagination":{
					"pageNo":currentPage,
					"pageSize":pageSize,
				},
				"conditionList":[
					{"value":JSON.stringify(facultyId.value),"key":"faculty_id","operator":"="}
				]
			}
		}else if(searchFacultyIds.value.length==0 && name.value==null){
			objForSearch.value = {
				"pagination":{
					"pageNo":currentPage,
					"pageSize":pageSize,
				},
				"conditionList":[]
			}
		}else if(searchFacultyIds.value.length!=0 && name.value!=null){
			if(searchFacultyIds.value[1] == null){
				facultyId.value=searchFacultyIds.value[0]
			}else{
				facultyId.value=searchFacultyIds.value[1]
			}
			objForSearch.value = {
				"pagination":{
					"pageNo":currentPage,
					"pageSize":pageSize,
				},
				"conditionList":[
					{"value":name,"key":"name","operator":"LIKE"},
					{"value":JSON.stringify(facultyId.value),"key":"faculty_id","operator":"="}
				]
			}
		}
		proxy.$http.post(
		'/userFindAll',
		objForSearch.value,
		{"headers":{"token":window.sessionStorage.getItem("token")}}
		)
		.then(res => {
			tableData.value=res.data.data;//把获取的服务端数据数组传递给tableData
			pageCount.value=res.data.totalPages;
			name.value='';
			searchFacultyIds.value=[]
		})
		.catch(err => {
			console.log(err)
		});
	}
	
	
	//文本框输入内容校验
	const isNum = (rule, value, callback) => {
		const username = /^[0-9]*$/
		if(value==''||value==null)  //补充了非空和长度校验
		    callback(new Error('用户名不能为空!'))
		else if(value.length<9||value.length<11)
			callback(new Error('用户名数字个数应为4至8!'))
		else if (!username.test(value)) {
			callback(new Error('请输入数字!'))
		} else {
			callback()
		}	  
	
	};
	const formRules = reactive({
		username: [
		  {required: true, message: '请输入账号', trigger: 'blur'}, //非空校验
		  {min: 9, max: 11, message: '长度在 9 到 11 个字符', trigger: 'blur'},  //长度校验
		  //{validator: isNum, trigger: 'blur'}  // validator是指用isNum方法做校验，可全部都用方法校验
		],		
		name: [
		  {required: true, message: '请输入姓名', trigger: 'blur'},
		  {min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur'}
		]		
	})
	
	import * as echarts from 'echarts'
	let echartsVisible=ref(false)
	let xData = {}
	let arrLength=0;
	function echartsBar(){
		echartsVisible.value=true
		//构建图表数据
		xData={types:[],values:[]} //图表横轴上显示名称及统计数字
		proxy.$http.get(
		"/facultyFindAll",
		{"headers":{"token":window.sessionStorage.getItem("token")}}
		).then(res => {
			// 学院个数
			arrLength=res.data.data.length;
			 // 此处的item涵盖一个学员的名称和id，因为/findAllSchoolName返回的只有这些内容
			res.data.data.forEach((item,index)=>{ // 循环每个学院
				//对每个学院请求其下的专业
				proxy.$http.get(
				'/userFindByFacultyId?id='+item.id,
				{"headers":{"token":window.sessionStorage.getItem("token")}}
				).then((response) => {
					//学院名放入数组
					xData.types.push(item.description);
					//每个学院专业个数存入
					xData.values.push(response.data.data.length);
					console.log(response.data.data.length)
					if(xData.values.length==arrLength)
					/*全部请求后再绘制，不能把draw放在then外，
					因为这样即便then没结束，也会调用then后的，导致图表内容不完整*/
						draw()					 
				})							
			});
		})
		//draw()	
	}
	
	function draw(){
		let myChart = echarts.init(document.getElementById("myChart")); 
		myChart.setOption({
			title: {
				text: "按部门统计用户个数"
			},
			tooltip: {
			    trigger: 'axis'  //移上显示tip
			  },
			xAxis: {
				axisLabel:{
						interval:0, //控制X轴刻度全部显示
						rotate:25 //倾斜角度
					},
				data: xData.types
			},
			yAxis: {
				    type: 'value',
				    axisLabel: {
				      formatter: '{value} 个'
				    },
					minInterval:1  //坐标不允许有小数
			},
			series: [{
				name: "用户数:",
				type: "bar",
				barCategoryGap:0,
				barWidth:50,
				data: xData.values,
				showBackground: true,
				backgroundStyle: {color: 'rgba(180, 180, 180, 0.2)'}
			}, ],
		});
	}		
</script>
